use tauri::command;
use crate::ctp_commands::ctp::types::{ApiResponse, AccountInfo, PositionInfo, InstrumentInfo, OrderInfo};
use crate::ctp_commands::ctp::state::*;
use crate::ctp_commands::ctp::utils::{get_next_request_id};
use crate::logger;

// 查询账户资金
#[command]
pub async fn query_account(
    session_id: String,
) -> ApiResponse<AccountInfo> {
    println!("🔍 [DEBUG] query_account called with session_id: {}", session_id);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = get_trader_login_status().lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = get_trader_apis().lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 真实调用CTP查询账户接口
            use ctp_trade_lib::*;

            // 创建查询账户请求结构
            let mut req = CThostFtdcQryTradingAccountField::default();

            // 获取登录信息以填充请求字段
            let login_info = {
                let login_infos = get_session_login_info().lock().unwrap();
                login_infos.get(&session_id).cloned()
            };

            if let Some(ref config) = login_info {
                // 填充查询请求字段
                let broker_id_bytes = config.broker_id.as_bytes();
                let investor_id_bytes = config.account.as_bytes();

                // 复制到固定长度数组，转换u8到i8
                let broker_len = std::cmp::min(broker_id_bytes.len(), req.BrokerID.len() - 1);
                let investor_len = std::cmp::min(investor_id_bytes.len(), req.InvestorID.len() - 1);

                for i in 0..broker_len {
                    req.BrokerID[i] = broker_id_bytes[i] as i8;
                }
                for i in 0..investor_len {
                    req.InvestorID[i] = investor_id_bytes[i] as i8;
                }
            }

            // 获取唯一的请求ID
            let request_id = get_next_request_id();

            println!("🔍 [INFO] Starting real CTP account query with request_id: {}", request_id);

            // 重置查询状态
            {
                let mut query_complete = get_account_query_complete().lock().unwrap();
                *query_complete = false;

                let mut account_data = get_ctp_account_data().lock().unwrap();
                *account_data = None;
            }

            // 添加延迟以避免查询频率过快
            std::thread::sleep(std::time::Duration::from_millis(1000));

            // 调用查询账户接口
            let result = api.req_qry_trading_account(&mut req, request_id);

            if result == 0 {
                println!("✅ [SUCCESS] CTP req_qry_trading_account called successfully, waiting for callback...");

                // 等待回调完成，设置合理的超时时间
                let mut wait_count = 0;
                let max_wait = 300; // 30秒，每次等待100ms

                println!("⏳ [INFO] Waiting for CTP account query callback...");

                loop {
                    std::thread::sleep(std::time::Duration::from_millis(100));
                    wait_count += 1;

                    let query_complete = get_account_query_complete().lock().unwrap();
                    if *query_complete {
                        drop(query_complete);

                        let account_data = get_ctp_account_data().lock().unwrap();
                        if let Some(account_info) = account_data.clone() {
                            drop(account_data);

                            println!("✅ [SUCCESS] CTP account query completed, balance={:.2}", account_info.balance);
                            
                            // 记录账户查询成功日志
                            logger::log_account_query(&account_info.broker_id, &account_info.account_id, true, None);
                            
                            return Ok(account_info);
                        } else {
                            println!("⚠️ [WARNING] CTP account query completed but no data");
                            return Err("CTP账户查询完成但未获取到数据".to_string());
                        }
                    }

                    if wait_count >= max_wait {
                        println!("⏰ [TIMEOUT] CTP account query timeout after 30 seconds");
                        return Err("CTP账户查询超时（30秒），请检查网络连接和CTP服务状态".to_string());
                    }
                }
            } else {
                println!("❌ [ERROR] CTP req_qry_trading_account failed with code: {}", result);
                return Err(format!("CTP账户查询失败，错误代码: {}", result));
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(account_info)) => {
            println!("✅ [SUCCESS] Account query successful");
            
            // 记录账户查询成功日志
            logger::log_account_query(&account_info.broker_id, &account_info.account_id, true, None);
            
            ApiResponse {
                success: true,
                data: Some(account_info),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Account query failed: {}", error);
            
            // 记录账户查询失败日志
            logger::log_account_query("unknown", "unknown", false, Some(&error));
            
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Account query panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 查询持仓信息
#[command]
pub async fn query_position(
    session_id: String,
) -> ApiResponse<Vec<PositionInfo>> {
    println!("🔍 [DEBUG] query_position called with session_id: {}", session_id);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = get_trader_login_status().lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = get_trader_apis().lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 真实调用CTP查询持仓接口
            use ctp_trade_lib::*;

            // 创建查询持仓请求结构
            let mut req = CThostFtdcQryInvestorPositionField::default();

            // 获取登录信息以填充请求字段
            let login_info = {
                let login_infos = get_session_login_info().lock().unwrap();
                login_infos.get(&session_id).cloned()
            };

            if let Some(ref config) = login_info {
                // 填充查询请求字段
                let broker_id_bytes = config.broker_id.as_bytes();
                let investor_id_bytes = config.account.as_bytes();

                // 复制到固定长度数组，转换u8到i8
                let broker_len = std::cmp::min(broker_id_bytes.len(), req.BrokerID.len() - 1);
                let investor_len = std::cmp::min(investor_id_bytes.len(), req.InvestorID.len() - 1);

                for i in 0..broker_len {
                    req.BrokerID[i] = broker_id_bytes[i] as i8;
                }
                for i in 0..investor_len {
                    req.InvestorID[i] = investor_id_bytes[i] as i8;
                }
            }

            // 获取唯一的请求ID
            let request_id = get_next_request_id();

            println!("🔍 [INFO] Starting real CTP position query with request_id: {}", request_id);

            // 重置查询状态
            {
                let mut query_complete = get_positions_query_complete().lock().unwrap();
                *query_complete = false;

                let mut positions_data = get_ctp_positions_data().lock().unwrap();
                positions_data.clear();
            }

            // 添加延迟以避免查询频率过快
            std::thread::sleep(std::time::Duration::from_millis(1000));

            // 调用查询持仓接口
            let result = api.req_qry_investor_position(&mut req, request_id);

            if result == 0 {
                println!("✅ [SUCCESS] CTP req_qry_investor_position called successfully, waiting for callback...");

                // 等待回调完成，设置合理的超时时间
                let mut wait_count = 0;
                let max_wait = 300; // 30秒，每次等待100ms

                println!("⏳ [INFO] Waiting for CTP position query callback...");

                loop {
                    std::thread::sleep(std::time::Duration::from_millis(100));
                    wait_count += 1;

                    let query_complete = get_positions_query_complete().lock().unwrap();
                    if *query_complete {
                        drop(query_complete);

                        let positions_data = get_ctp_positions_data().lock().unwrap();
                        let result_data = positions_data.clone();
                        drop(positions_data);

                        println!("✅ [SUCCESS] CTP position query completed, found {} real positions", result_data.len());
                        
                        // 记录持仓查询成功日志
                        if let Some(ref config) = login_info {
                            logger::log_position_query(&config.broker_id, &config.account, None, true, None);
                        }
                        
                        return Ok(result_data);
                    }

                    if wait_count >= max_wait {
                        println!("⏰ [TIMEOUT] CTP position query timeout after 30 seconds");
                        return Err("CTP持仓查询超时（30秒），请检查网络连接和CTP服务状态".to_string());
                    }
                }
            } else {
                println!("❌ [ERROR] CTP req_qry_investor_position failed with code: {}", result);
                return Err(format!("CTP持仓查询失败，错误代码: {}", result));
            }
        } else {
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(positions)) => {
            println!("✅ [SUCCESS] Position query initiated, {} positions", positions.len());
            ApiResponse {
                success: true,
                data: Some(positions),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Position query failed: {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Position query panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 查询合约信息 - 完全通过真实CTP API获取
#[command]
pub async fn query_instruments(
    session_id: String,
) -> ApiResponse<Vec<InstrumentInfo>> {
    println!("🔍 [DEBUG] query_instruments called with session_id: {}", session_id);

    match std::panic::catch_unwind(|| {
        // 首先检查登录状态
        let login_status = get_trader_login_status().lock().unwrap();
        if !login_status.get(&session_id).unwrap_or(&false) {
            drop(login_status); // 释放锁
            
            println!("⚠️ [WARNING] CTP API not connected");
            
            // 记录未登录日志
            logger::log_instrument_query(None, false, None, Some("CTP API not connected"));
            
            // 返回未登录错误
            return Err("CTP 交易 API 未连接，请先登录".to_string());
        }
        drop(login_status); // 释放锁

        let mut apis = get_trader_apis().lock().unwrap();

        if let Some(api) = apis.get_mut(&session_id) {
            println!("✅ [DEBUG] Found Trader API for session: {}", session_id);

            // 真实调用CTP查询接口
            use ctp_trade_lib::*;

            // 创建查询合约请求结构
            let mut req = CThostFtdcQryInstrumentField::default();

            // 获取唯一的请求ID
            let request_id = get_next_request_id();

            println!("🔍 [INFO] Starting real CTP instrument query with request_id: {}", request_id);

            // 添加延迟以避免查询频率过快
            std::thread::sleep(std::time::Duration::from_millis(1000));

            // 调用查询合约接口
            let result = api.req_qry_instrument(&mut req, request_id);

            if result == 0 {
                println!("✅ [SUCCESS] CTP req_qry_instrument called successfully, waiting for callback...");

                // 重置查询状态
                {
                    let mut query_complete = get_instruments_query_complete().lock().unwrap();
                    *query_complete = false;

                    let mut instruments_data = get_ctp_instruments_data().lock().unwrap();
                    instruments_data.clear();
                }

                // 等待回调完成，设置合理的超时时间
                let mut wait_count = 0;
                let max_wait = 300; // 30秒，每次等待100ms

                println!("⏳ [INFO] Waiting for CTP instrument query callback...");

                loop {
                    std::thread::sleep(std::time::Duration::from_millis(100));
                    wait_count += 1;

                    let query_complete = get_instruments_query_complete().lock().unwrap();
                    if *query_complete {
                        drop(query_complete);

                        let instruments_data = get_ctp_instruments_data().lock().unwrap();
                        let result_data = instruments_data.clone();
                        drop(instruments_data);

                        if result_data.len() > 0 {
                            println!("✅ [SUCCESS] CTP query completed, found {} real instruments", result_data.len());
                            
                            // 记录合约查询成功日志
                            logger::log_instrument_query(None, true, Some(result_data.len()), None);
                            
                            return Ok(result_data);
                        } else {
                            println!("⚠️ [WARNING] CTP query completed but no instruments found");
                            
                            // 记录合约查询成功但无数据的日志
                            logger::log_instrument_query(None, true, Some(0), Some("No instruments found"));
                            
                            break;
                        }
                    }

                    if wait_count >= max_wait {
                        println!("⏰ [TIMEOUT] CTP query timeout after 30 seconds");
                        
                        // 记录超时日志
                        logger::log_instrument_query(None, false, None, Some("Query timeout after 30 seconds"));
                        
                        // 返回超时错误，让前端处理缓存逻辑
                        return Err("QUERY_TIMEOUT".to_string());
                    }
                }

                // 如果查询完成但没有数据，返回错误
                println!("⚠️ [NO_DATA] CTP query completed but no instruments found");
                
                // 记录查询完成但无数据的日志
                logger::log_instrument_query(None, true, Some(0), Some("No instruments found in query"));
                
                // 返回无数据错误
                return Err("查询完成但未获取到合约数据".to_string());
            } else {
                println!("❌ [ERROR] CTP req_qry_instrument failed with code: {}", result);
                
                // 记录查询失败日志
                logger::log_instrument_query(None, false, None, Some(&format!("Query failed with code {}", result)));
                
                // 返回查询失败错误
                return Err(format!("CTP合约查询失败，错误代码: {}", result));
            }
        } else {
            println!("⚠️ [WARNING] Session ID {} not found", session_id);
            
            // 记录会话未找到日志
            logger::log_instrument_query(None, false, None, Some(&format!("Session ID {} not found", session_id)));
            
            // 返回会话未找到错误
            Err(format!("Session ID {} not found", session_id))
        }
    }) {
        Ok(Ok(instruments)) => {
            println!("✅ [SUCCESS] Instruments query initiated, {} instruments", instruments.len());
            ApiResponse {
                success: true,
                data: Some(instruments),
                error: None,
            }
        },
        Ok(Err(error)) => {
            println!("❌ [ERROR] Instruments query failed: {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        },
        Err(_) => {
            let error = "Instruments query panicked".to_string();
            println!("❌ [ERROR] {}", error);
            ApiResponse {
                success: false,
                data: None,
                error: Some(error),
            }
        }
    }
}

// 查询账号下所有未成交订单
#[command]
pub async fn query_all_orders(session_id: String) -> ApiResponse<Vec<OrderInfo>> {
    println!("🔍 [DEBUG] query_all_orders called with session_id: {}", session_id);

    // 检查登录状态
    let is_logged_in = {
        let login_status = get_trader_login_status().lock().unwrap();
        login_status.get(&session_id).unwrap_or(&false).clone()
    };

    if !is_logged_in {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("请先登录CTP交易系统".to_string()),
        };
    }

    // 检查Trader API是否存在
    let api_exists = {
        let apis = get_trader_apis().lock().unwrap();
        apis.contains_key(&session_id)
    };

    if !api_exists {
        return ApiResponse {
            success: false,
            data: None,
            error: Some("未找到Trader API".to_string()),
        };
    }

    // 获取登录信息
    let login_info = {
        let login_infos = get_session_login_info().lock().unwrap();
        login_infos.get(&session_id).cloned()
    };

    let account_config = match login_info {
        Some(config) => config,
        None => {
            return ApiResponse {
                success: false,
                data: None,
                error: Some("未找到登录信息".to_string()),
            };
        }
    };

    // 生成请求ID
    let request_id = get_next_request_id();

    // 构造查询订单请求
    let mut req = ctp_trade_lib::CThostFtdcQryOrderField::default();

    // 设置查询参数
    let broker_id_bytes = account_config.broker_id.as_bytes();
    let investor_id_bytes = account_config.account.as_bytes();

    // 安全地复制字符串到固定长度数组，转换u8到i8
    let broker_len = std::cmp::min(broker_id_bytes.len(), req.BrokerID.len() - 1);
    let investor_len = std::cmp::min(investor_id_bytes.len(), req.InvestorID.len() - 1);

    for i in 0..broker_len {
        req.BrokerID[i] = broker_id_bytes[i] as i8;
    }
    for i in 0..investor_len {
        req.InvestorID[i] = investor_id_bytes[i] as i8;
    }

    // 清空之前的查询结果
    {
        let mut queried_orders = get_queried_orders().lock().unwrap();
        queried_orders.insert(session_id.clone(), Vec::new());
    }

    // 调用CTP查询接口
    let result = {
        let mut apis = get_trader_apis().lock().unwrap();
        if let Some(api) = apis.get_mut(&session_id) {
            api.req_qry_order(&mut req, request_id)
        } else {
            -1
        }
    };

    if result == 0 {

        // 等待查询结果（最多等待3秒）
        for i in 0..30 {
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

            let queried_orders = get_queried_orders().lock().unwrap();
            if let Some(orders) = queried_orders.get(&session_id) {
                if !orders.is_empty() || i >= 29 {
                    let orders_clone = orders.clone();
                    drop(queried_orders);

                    return ApiResponse {
                        success: true,
                        data: Some(orders_clone),
                        error: None,
                    };
                }
            }
        }

        // 超时或无订单
        ApiResponse {
            success: true,
            data: Some(Vec::new()),
            error: Some("查询超时，未收到CTP响应".to_string()),
        }
    } else {
        ApiResponse {
            success: false,
            data: None,
            error: Some(format!("订单查询请求失败，错误代码: {}", result)),
        }
    }
}

// 查询指定订单的剩余未成交数量
#[command]
pub async fn query_order_remaining_volume(session_id: String, order_ref: String) -> ApiResponse<i32> {
    // 获取所有订单
    let orders_result = query_all_orders(session_id).await;

    if orders_result.success {
        // 查找指定的订单
        for order in orders_result.data.unwrap_or_default() {
            if order.order_ref == order_ref {
                let remaining = order.volume - order.volume_traded;
                return ApiResponse {
                    success: true,
                    data: Some(remaining),
                    error: None,
                };
            }
        }
        // 订单未找到
        ApiResponse {
            success: false,
            data: None,
            error: Some("订单未找到".to_string()),
        }
    } else {
        ApiResponse {
            success: false,
            data: None,
            error: orders_result.error,
        }
    }
}

// 查询所有订单的剩余未成交数量汇总
#[command]
pub async fn query_all_remaining_volumes(session_id: String) -> ApiResponse<Vec<(String, i32)>> {
    let orders_result = query_all_orders(session_id).await;

    if orders_result.success {
        let mut remaining_volumes = Vec::new();

        for order in orders_result.data.unwrap_or_default() {
            let remaining = order.volume - order.volume_traded;
            if remaining > 0 {  // 只返回还有未成交数量的订单
                remaining_volumes.push((order.order_ref, remaining));
            }
        }

        ApiResponse {
            success: true,
            data: Some(remaining_volumes),
            error: None,
        }
    } else {
        ApiResponse {
            success: false,
            data: None,
            error: orders_result.error,
        }
    }
}

